package com.gientech.consulconsumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@RestController
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("consumer-test")
    public  String test(){

        //方法1
        //String rst =  restTemplate.getForObject("http://127.0.0.1:8001/pro-test", String.class);
        //方法2
        //String rst =  restTemplate.getForObject("http://provider/pro-test", String.class);

        //方法3
        List<ServiceInstance> instances = this.discoveryClient.getInstances("provider");
        ServiceInstance serviceInstance = instances.get(0);
        URI uri = serviceInstance.getUri();
        String targetUrl = uri +"/pro-test";
        String rst =  restTemplate.getForObject(targetUrl, String.class);

        return "consumer "+rst;
    }

}


